from DrissionPage import ChromiumPage
from util import dp_helpe_V_file, cv2_util_V_file, file_helper, my_tkinter
from pojo.Product import *
from pojo.File import File
from util import pandas_util, re_util
from time import sleep


class cpss_产品搜索:
    def __init__(
        self,
        page_xz_下载: dp_helpe_V_file.xz_下载_class,
        site,
        tzdsl_特征点数量=30,
    ) -> None:
        page = ChromiumPage()
        self.page = page
        self.page_xz_下载 = page_xz_下载
        self.site = site
        self.tzdsl_特征点数量 = tzdsl_特征点数量

    def close(self):
        self.page.close()

    def get_list_product_获取产品列表(self) -> list[Product]:
        pass

    def get_list_img_获取相似图片列表(self) -> list[Product]:
        list_product = self.get_list_product_获取产品列表()
        list_product_out = []
        # img_folder = "img"
        i = 0
        for i_pro in list_product:
            print(f"cpss33  正在判断图片相似性  {i}")
            i_file = File(folder_path=self.file.folder_path, file_qz="i_file")
            self.page_xz_下载.xzwj_下载文件(url=i_pro.url_img, file=i_file)
            bl = cv2_util_V_file.pdtpsfxs_判断图片是否相似(
                file_img1=i_file,
                file_img2=self.file,
                tzdsl_特征点数量=self.tzdsl_特征点数量,
                # sfksh_是否可视化=True,
            )
            if bl:
                print("cpss相似--------" + i_pro.url_img)
                list_product_out.append(i_pro)
                return list_product_out
            # print("tpss38   " + str(bl))
            i += 1
        return list_product_out

    def get_series_product_获取第一个相似的产品(self, file: File):
        list_pro = self.get_list_img_获取相似图片列表(file=file)
        if len(list_pro) == 0:
            return None
        return list_pro[0].get_series()

    # def get_ser_产品汇总(self, file: File):
    def get_ser_产品汇总(self, file: File, prod: Product):
        self.file = file
        self.prod = prod
        list_pro = self.get_list_img_获取相似图片列表()
        if len(list_pro) == 0:
            return None
        list_ser = []
        for pro in list_pro:
            ser = pro.get_series()
            list_ser.append(ser)
        df = pandas_util.get_df_series_纵向合并为df(list_ser=list_ser)
        # ser_产品 = df[df[f"{self.site}-价格"] == df[f"{self.site}-价格"].min()].iloc[0]
        numeric_df = df[
            pd.to_numeric(df[f"{self.site}-价格"], errors="coerce").notnull()
        ]
        ser_产品 = numeric_df.loc[
            numeric_df[f"{self.site}-价格"].astype(float).idxmin()
        ]
        # ser_产品["相似产品数量"] = len(list_pro)
        ser_产品.loc[f"{self.site}-相似产品数量"] = len(list_pro)
        return ser_产品


class tpss_1688图片搜索(cpss_产品搜索):
    def __init__(
        self,
        page_xz_下载: dp_helpe_V_file.xz_下载_class,
        site=str(1688),
        tzdsl_特征点数量=30,
    ) -> None:
        super().__init__(page_xz_下载, site=site, tzdsl_特征点数量=tzdsl_特征点数量)
        self.page.get("https://www.1688.com/")

    def get_list_product_获取产品列表(self) -> list[Product]:
        list_pro_out = []

        def sctp_上传图片(page: ChromiumPage):
            a = page.eles("以图搜款")
            # a[1].click.to_upload(img_path)
            a[1].click.to_upload(self.file.get_file_path())
            page.wait.doc_loaded()

        while True:
            print("101")
            tab = dp_helpe_V_file.hqxbqy_网页操作_获取新标签页(
                self.page, sctp_上传图片, "批发_供应_阿里巴巴", time=9
            )
            if tab == None:
                # my_tkinter.文本框("没有找到1688标签页，准备重试")
                print("cpss105  没有找到1688标签页")
                tab = dp_helpe_V_file.hqxbqy_网页操作_获取新标签页(
                    self.page, None, "批发_供应_阿里巴巴", time=9
                )
                if not tab is None:
                    break
            else:
                break
        es = tab.eles("x://div[@class='space-offer-card-box']")
        for e in es:
            e_a = e.ele("x://div[@class='img-container']//a")
            url_e = e_a.attr("href")
            e_img = e.ele("x://div[@class='img']")
            img_url = e_img.attr("style")
            img_url = img_url.replace('background-image: url("', "")
            img_url = img_url[:-3]
            price = e.ele("x://div[@class='price']").text
            title = e.ele("x://div[@class='title']").text
            pro_1688 = Product(
                price=price, url=url_e, url_img=img_url, title=title, site=self.site
            )
            list_pro_out.append(pro_1688)
        tab.close()
        return list_pro_out
        # return super().__get_list_url_img_获取图片url列表(file)


class cpss_ama_亚马逊产品搜索(cpss_产品搜索):
    def get_list_tpss_图片搜索(self):
        list_pro = []
        # 跳转页面
        if True:
            if self.site == "亚马逊德国":
                self.page.get("https://www.amazon.de/stylesnap/")
            elif self.site == "亚马逊日本":
                self.page.get("https://www.amazon.co.jp/stylesnap")
            elif self.site == "亚马逊美国":
                self.page.get("https://www.amazon.com/stylesnap/")
            else:
                raise Exception(f"cpss138 错误，无法匹配站点  site:{self.site}")
            self.page.wait.doc_loaded()
        e_img_upload = self.page.ele(
            "x://input[@class='a-button-input' and @type='file']"
        )
        e_img_upload.click.to_upload(self.file.get_file_path())
        self.page.wait.doc_loaded()
        list_e = self.page.eles("x://article[@class='cellContainer']")
        for e in list_e:
            price = 999
            e_price = e.ele("x://div[@class='prices']//span")
            if e_price:
                price = e_price.text
                # price = str(e_price.text)
                # price.replace(",", ".")
                # price = re_util.get_list_tqsz_提取数字(price)[0]
            url = e.ele("x://section[@class='item-image-container']//a").attr("href")
            url_img = e.ele("x://img").attr("src")
            e_score = e.ele("x://div[@class='star-rating']", timeout=0)
            score = ""
            num_comm = ""
            if e_score:
                score = e_score.ele("x://p[@class='value']").text
                num_comm = e_score.ele("x://p[@class='count']").text
            pro_ama = Product_Amazon(
                price=price,
                url=url,
                url_img=url_img,
                title="",
                site=self.site,
                score=score,
                number_comments=num_comm,
            )
            # print("cpss158")
            # print(self.site)
            # print(pro_ama.test())
            # print(pro_ama.get_series().index)
            list_pro.append(pro_ama)
            # print(pro_ama.get_set())
            # print(pro_ama.get_series())
        return list_pro

    def get_list_btss_标题搜索(self):
        list_pro = []
        # 跳转页面
        print(f"cpss172  {self.site}")
        if True:
            # str_xpath_submit = "x://input[@id='nav-search-submit-button']"
            list_xpath = [
                "x://input[@id='nav-search-submit-button']",
                "//input[@type='submit']",
            ]
            url_zd_站点url = "https://www.amazon.com"
            if self.site == "亚马逊加拿大":
                url_zd_站点url = "https://www.amazon.ca"
            dp_helpe_V_file.tzym_跳转页面(
                url=url_zd_站点url,
                page=self.page,
                # str_xpath="//div[@data-asin]",
                str_xpath=list_xpath,
            )
            # self.page.wait.doc_loaded()
        e_input = self.page.ele("x://input[@type='text']")
        e_input.input(self.prod.title)
        e_submit = self.page.ele("x://input[@id='nav-search-submit-button']")
        e_submit.click()
        self.page.wait.doc_loaded()
        es = None
        list_xpath = [
            "x://div[@class='a-section a-spacing-base']",
            "x://div[@class='s-main-slot s-result-list s-search-results sg-row']/div[@data-asin and string-length(@data-asin) > 0]",
        ]
        i = 0
        while True:
            print(f"219")
            for xpath in list_xpath:
                es = self.page.eles(xpath, timeout=0)
                if es:
                    break
            if len(es) == 0:
                i += 1
                print(f"cpss213   没有捕捉到产品列表")
                if i >= 6:
                    my_tkinter.文本框("cpss213   没有捕捉到产品列表")
                    i = 0
                sleep(1)
            else:
                break

        i = 0
        for e in es:
            i += 1
            # print(f"cpss215  {i}")
            price = 999
            e_price = e.ele("x://span[@class='a-offscreen']", timeout=0)
            if e_price:
                price = e_price.text
            e_a = e.ele(
                "x://a[@class='a-link-normal s-underline-text s-underline-link-text s-link-style a-text-normal']",
                timeout=0,
            )
            url = e_a.attr("href")
            url_img = e.ele("x://img", timeout=0).attr("src")
            # print(f"cpss218  url_img  {url_img}")
            title = e_a.ele("x:/span", timeout=0).text
            e_s = e.eles("x://div[@class='a-row a-size-small']/span", timeout=0)
            score = ""
            number_comments = ""
            if e_s:
                score = e_s[0].attr("aria-label")
                number_comments = e_s[1].ele("x://span").text
            prod = Product_Amazon(
                price=price,
                url=url,
                url_img=url_img,
                site=self.site,
                title=title,
                score=score,
                number_comments=number_comments,
            )
            list_pro.append(prod)
            if i >= 10:
                break
        return list_pro

    def get_list_btss_标题搜索1(self, bz_步骤=1):
        list_pro = []
        # 跳转页面
        # print(f"cpss172  {self.site}")
        if bz_步骤 == 1:
            print(f"cpss274 步骤1")
            # str_xpath_submit = "x://input[@id='nav-search-submit-button']"
            list_xpath = [
                "x://input[@id='nav-search-submit-button']",
                "//input[@type='submit']",
            ]
            url_zd_站点url = "https://www.amazon.com"
            if self.site == "亚马逊加拿大":
                url_zd_站点url = "https://www.amazon.ca"
            dp_helpe_V_file.tzym_跳转页面(
                url=url_zd_站点url,
                page=self.page,
                # str_xpath="//div[@data-asin]",
                str_xpath=list_xpath,
            )
            # self.page.wait.doc_loaded()
            e_input = self.page.ele("x://input[@type='text']")
            e_input.input(self.prod.title)
            e_submit = self.page.ele("x://input[@id='nav-search-submit-button']")
            e_submit.click()
            self.page.wait.doc_loaded()
            if not self.page.ele("x://div[@data-asin]", timeout=6):
                print(f"pcss296   没有找到产品列表")
                sleep(0.3)
                return self.get_list_btss_标题搜索1(bz_步骤=1)
            else:
                bz_步骤 = 2
        if bz_步骤 == 2:
            print(f"cpss301 步骤2")
            es = None
            list_xpath = [
                "x://div[@class='a-section a-spacing-base']",
                "x://div[@class='s-main-slot s-result-list s-search-results sg-row']/div[@data-asin and string-length(@data-asin) > 0]",
            ]
            i = 0
            while True:
                print(f"310")
                for xpath in list_xpath:
                    es = self.page.eles(xpath, timeout=0)
                    if es:
                        break
                if len(es) == 0:
                    i += 1
                    print(f"cpss213   没有捕捉到产品列表")
                    if i >= 6:
                        my_tkinter.文本框("cpss213   没有捕捉到产品列表")
                        return []
                        i = 0
                    sleep(1)
                else:
                    bz_步骤 = 3
                    break
        if bz_步骤 == 3:
            print(f"cpss324 步骤3")
            i = 0
            for e in es:
                i += 1
                price = 999
                e_price = e.ele("x://span[@class='a-offscreen']", timeout=0)
                if e_price:
                    price = e_price.text
                e_a = e.ele(
                    "x://a[@class='a-link-normal s-underline-text s-underline-link-text s-link-style a-text-normal']",
                    timeout=0,
                )
                url = e_a.attr("href")
                url_img = e.ele("x://img", timeout=0).attr("src")
                # print(f"cpss218  url_img  {url_img}")
                title = e_a.ele("x:/span", timeout=0).text
                e_s = e.eles("x://div[@class='a-row a-size-small']/span", timeout=0)
                score = ""
                number_comments = ""
                if e_s:
                    score = e_s[0].attr("aria-label")
                    number_comments = e_s[1].ele("x://span").text
                prod = Product_Amazon(
                    price=price,
                    url=url,
                    url_img=url_img,
                    site=self.site,
                    title=title,
                    score=score,
                    number_comments=number_comments,
                )
                list_pro.append(prod)
                if i >= 10:
                    break
            return list_pro

    def get_list_product_获取产品列表(self) -> list[Product]:
        if self.site in ["亚马逊德国", "亚马逊日本"]:
            li = self.get_list_tpss_图片搜索()
            print("cpss172-执行了图片搜索")
        elif self.site in ["亚马逊加拿大"]:
            # li = self.get_list_btss_标题搜索()
            print("cpss370-执行了标题搜索")
            li = self.get_list_btss_标题搜索1()
        else:
            raise Exception("cpss236 错误，无法判断执行什么流程")
        return li

    def test(self):
        print(self.site)
